<template>
  <div class="page">
    <h2>物质使用与成瘾管理</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/档案号/物质搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="substanceFilter" placeholder="物质类型" style="width:180px">
        <el-option label="全部" :value="''" />
        <el-option label="酒精" value="alcohol" />
        <el-option label="烟草" value="tobacco" />
        <el-option label="药物" value="drug" />
        <el-option label="其他" value="other" />
      </el-select>

      <el-select v-model="statusFilter" placeholder="管理状态" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="治疗中" value="treatment" />
        <el-option label="康复中" value="recovery" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增记录</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="recordId" label="档案号" width="140" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="substance" label="物质类型" width="140" />
      <el-table-column prop="severity" label="严重度" width="120" />
      <el-table-column prop="lastUse" label="最近使用" width="140" />
      <el-table-column prop="assigned" label="负责医师" width="140" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status==='treatment'? 'warning' : 'success'">{{ row.status==='treatment' ? '治疗中' : '康复中' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.recordId)">编辑</el-button>
          <el-button size="small" @click="markRecovery(row.recordId)" style="margin-left:8px">标记康复</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.recordId)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchMarkRecovery">批量标记康复</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑记录' : '新增记录'" v-model="showModal" width="620px">
      <el-form :model="form" label-width="140px">
        <el-form-item label="档案号"><el-input v-model="form.recordId" /></el-form-item>
        <el-form-item label="姓名"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="物质类型">
          <el-select v-model="form.substance" style="width:220px">
            <el-option label="酒精" value="alcohol" />
            <el-option label="烟草" value="tobacco" />
            <el-option label="药物" value="drug" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重度"><el-select v-model="form.severity" style="width:160px"><el-option label="轻度" value="mild" /><el-option label="中度" value="moderate" /><el-option label="重度" value="severe" /></el-select></el-form-item>
        <el-form-item label="最近使用"><el-input v-model="form.lastUse" placeholder="YYYY-MM-DD 或 间隔" /></el-form-item>
        <el-form-item label="负责医师"><el-input v-model="form.assigned" /></el-form-item>
        <el-form-item label="状态"><el-select v-model="form.status" style="width:160px"><el-option label="治疗中" value="treatment" /><el-option label="康复中" value="recovery" /></el-select></el-form-item>
        <el-form-item label="干预计划"><el-input v-model="form.plan" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const DEFAULT_DATA = [
  { recordId: 'A001', name: '刘某', substance: 'alcohol', severity: 'moderate', lastUse: '2025-10-10', assigned: '周医生', status: 'treatment', plan: '门诊药物维持+咨询' },
  { recordId: 'A002', name: '陈某', substance: 'drug', severity: 'severe', lastUse: '2025-09-01', assigned: '王医生', status: 'recovery', plan: '社区康复' }
];

const data = ref([]);
const q = ref('');
const substanceFilter = ref('');
const statusFilter = ref('');
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ recordId:'', name:'', substance:'alcohol', severity:'mild', lastUse:'', assigned:'', status:'treatment', plan:'' });

onMounted(()=>{ load(); });
function load(){ data.value = JSON.parse(JSON.stringify(DEFAULT_DATA)); }

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.name.toLowerCase().includes(qq) || String(d.recordId).toLowerCase().includes(qq) || (d.substance||'').toLowerCase().includes(qq))) return false;
    if(substanceFilter.value && d.substance !== substanceFilter.value) return false;
    if(statusFilter.value && d.status !== statusFilter.value) return false;
    return true;
  });
});

watch(selectedRows, v=>{ selectedIds.value = v.map(i=>i.recordId); });
function onSelectionChange(rows){ selectedRows.value = rows; }

function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.recordId===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{recordId:'',name:'',substance:'alcohol',severity:'mild',lastUse:'',assigned:'',status:'treatment',plan:''}); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.recordId || !form.name){ ElMessage.warning('档案号和姓名为必填项'); return; }
  if(editingId.value){ const it = data.value.find(x=>x.recordId===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); }
  else{ data.value.push(JSON.parse(JSON.stringify(form))); }
  showModal.value=false; ElMessage.success('保存成功'); }

function deleteOne(id){ ElMessageBox.confirm('确认删除该记录？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.recordId!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}
function markRecovery(id){ const it = data.value.find(x=>x.recordId===id); if(it){ it.status='recovery'; ElMessage.success('已标记康复'); } }
function batchMarkRecovery(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.recordId)) d.status='recovery'; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.recordId)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['recordId','name','substance','severity','lastUse','assigned','status','plan'], ...data.value.map(d=>[d.recordId,d.name,d.substance,d.severity,d.lastUse,d.assigned||'',d.status,d.plan||'']) ];
  const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n');
  const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'});
  const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='addiction.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
}

function onClear(){}
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>